package com.put.mybills.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.LineGraphView;
import com.put.mybills.R;
import com.put.mybills.adapter.CalendarViewScrollable;
import com.put.mybills.adapter.GlobalParams;
import com.put.mybills.model.Bill;
import com.put.mybills.model.Facture;
import com.put.mybills.model.GraphViewData;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class GraphFragment extends Fragment{
	
	private String factureName;
	private Spinner graphFilter;
	
	private String TAG = "GraphFragment";
	
	
	public GraphFragment(String factureName) {
		this.factureName = factureName;
	}

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
	 
		  	final View rootView = inflater.inflate(R.layout.fragment_graph, container, false);
		  	graphFilter = (Spinner) rootView.findViewById(R.id.graphFilter);
		  	
		  	String[] values = getResources().getStringArray(R.array.graph_filter_items);        
		  	ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, values);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			
			graphFilter.setAdapter(adapter);
			
			graphFilter.setOnItemSelectedListener(new OnItemSelectedListener() {			
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {	
					
					RelativeLayout layout = (RelativeLayout) rootView.findViewById(R.id.graph);
					layout.removeAllViews();
					
					
					Facture facture = GlobalParams.getInstance().facturedatasource.getFacture(factureName);
				  	final List<Bill> allBills = GlobalParams.getInstance().billdatasource.getAllBills(facture.getId());
				  	Collections.sort(allBills);
				  	
				  	List<Bill> matchedBills = new ArrayList<Bill>();
				  	Calendar cal = Calendar.getInstance();				  	
				  	
				  	if (allBills.size()>1) {
				  		
				  		Log.d(TAG, "Position " + position);
				  		switch(position)
						{
						case 0: // all bills
							// allbills no change
							for(int i=0; i< allBills.size(); i++ ){								
								matchedBills.add(allBills.get(i));
							}
							break;
							
						case 1: // last three months
							Calendar threeMonth = Calendar.getInstance();				  	
						  	threeMonth.add(Calendar.MONTH, -3);
						  	
						  	final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					 		Log.d(TAG, " three months is " + sdf.format(threeMonth.getTime()));
						  	
							for(int i=0; i< allBills.size(); i++ ){								
								if ((allBills.get(i).getTmpDate().getTime() <= cal.getTime().getTime()) 
										&& allBills.get(i).getTmpDate().getTime() >= threeMonth.getTime().getTime()  )
									matchedBills.add(allBills.get(i));								
							}
							
							break;
							
						case 2: // last half year
							Calendar halfYear = Calendar.getInstance();				  	
							halfYear.add(Calendar.MONTH, -6); 
							for(int i=0; i< allBills.size(); i++ ){								
								if ((allBills.get(i).getTmpDate().getTime() <= cal.getTime().getTime()) 
										&& allBills.get(i).getTmpDate().getTime() >= halfYear.getTime().getTime()  )
									matchedBills.add(allBills.get(i));								
							}
							
							break;
							
						case 3: // last year
							Calendar lastYear = Calendar.getInstance();				  	
							lastYear.add(Calendar.YEAR, -1); 
							final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
					 		
							Log.d(TAG, " last year is  " + sdf1.format(lastYear.getTime()));
						  	
							for(int i=0; i< allBills.size(); i++ ){								
								if ((allBills.get(i).getTmpDate().getTime() <= cal.getTime().getTime()) 
										&& allBills.get(i).getTmpDate().getTime() >= lastYear.getTime().getTime()  )
									matchedBills.add(allBills.get(i));								
							}
							
							break;
							
						case 4: // customs
							
							
							final Dialog dialog = new Dialog(getActivity());
							dialog.setContentView(R.layout.custom_time_dialog);
							dialog.setTitle(getResources().getString(R.string.graph_filtr_title));
				 
							Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
							
							final CalendarViewScrollable beginDate = (CalendarViewScrollable)dialog.findViewById(R.id.calendarView1);
							final CalendarViewScrollable endDate = (CalendarViewScrollable)dialog.findViewById(R.id.calendarView2);
							
							// if button is clicked, close the custom dialog
							dialogButton.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									
									long end = endDate.getDate();
									long begin = beginDate.getDate();
									
									Log.d(TAG, "Begin date is " + new SimpleDateFormat("MM/dd/yyyy").format(new Date(begin)));
									Log.d(TAG, "End date is " + new SimpleDateFormat("MM/dd/yyyy").format(new Date(end)));
									
									
									List<Bill> matchedBills1 = new ArrayList<Bill>();
								  		
									for(int i=0; i< allBills.size(); i++ ){		
										Log.d(TAG, "Current date is " + new SimpleDateFormat("MM/dd/yyyy").format(new Date(allBills.get(i).getTmpDate().getTime())));
										
										if ((allBills.get(i).getTmpDate().getTime() >= begin) 
												&& allBills.get(i).getTmpDate().getTime() <= end  )											
											matchedBills1.add(allBills.get(i));		
									}
										
									if (matchedBills1.size()>1) {											
										
										GraphViewData[] data = new GraphViewData[matchedBills1.size()];		
									  	//Log.d("GRAPH", "SIZE " + allBills.size());			 
									  	for (int j=0; j<matchedBills1.size();j++){
									  	  	//Log.d("GRAPH", "Add i=" + i + " price= " + allBills.get(i).getPrice());
									  		data[j] = new GraphViewData(j, matchedBills1.get(j).getPrice());
										}
									  	
									  
										GraphView graphView = new LineGraphView( getActivity() , factureName + " Graph" );
										graphView.addSeries(new GraphViewSeries(data));
										graphView.setScrollable(true);
										
										/*String[] dates = new String[allBills.size()];				
										for (int i=0; i<allBills.size();i++){					
												dates[i] = allBills.get(i).getDate();
										}
										graphView.setHorizontalLabels(dates);
										*/
										RelativeLayout layout = (RelativeLayout) rootView.findViewById(R.id.graph);
								  		layout.removeAllViews();
										layout.addView(graphView);
									
										
									}
									
									
									dialog.dismiss();
								}
							});
				 
							dialog.show();
		
							break;
						}
				  		
				  		if (matchedBills.size()>1 && position != 4){
				  									  		
					  		GraphViewData[] data = new GraphViewData[matchedBills.size()];		
						  	//Log.d("GRAPH", "SIZE " + allBills.size());			 
						  	for (int i=0; i<matchedBills.size();i++){
						  	  	//Log.d("GRAPH", "Add i=" + i + " price= " + allBills.get(i).getPrice());
						  		data[i] = new GraphViewData(i, matchedBills.get(i).getPrice());
							}
						  	
						  
							GraphView graphView = new LineGraphView( getActivity() , factureName + " Graph" );
							graphView.addSeries(new GraphViewSeries(data));
							graphView.setScrollable(true);
							
							/*String[] dates = new String[allBills.size()];				
							for (int i=0; i<allBills.size();i++){					
									dates[i] = allBills.get(i).getDate();
							}
							graphView.setHorizontalLabels(dates);
							*/
							layout.removeAllViews();
							layout.addView(graphView);
				
				  		}
				  		else {
				  			

					  		TextView emptyBillList = new TextView(getActivity());
					  		emptyBillList.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
					  		emptyBillList.setText(R.string.graph_filtr_no_data);
					  		layout = (RelativeLayout) rootView.findViewById(R.id.graph);
					  		emptyBillList.setPadding(30, 30, 30, 30);
					  		layout.removeAllViews();
							layout.addView(emptyBillList);		
				
				  			
				  			
				  		}
				  	}
				  	else {
				  			
					  		TextView emptyBillList = new TextView(getActivity());
					  		emptyBillList.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
					  		emptyBillList.setText(R.string.facture_graph_data_not_exsist);
					  		layout = (RelativeLayout) rootView.findViewById(R.id.graph);
					  		emptyBillList.setPadding(30, 30, 30, 30);
					  		layout.removeAllViews();
							layout.addView(emptyBillList);		
					  	
				  	}
					
					
					
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
					// TODO Auto-generated method stub
					
				}
			});
			
	
	        return rootView;
	    }

}
